// Copyright 2019 orivil.com. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found at https://mit-license.org.

package utils

import (
	"gitee.com/tugoer/psy-testing/code/env"
	"github.com/pkg/errors"
	"io/ioutil"
	"net/http"
	"net/url"
	"regexp"
)

var dataReg = regexp.MustCompile("var gameData =\\s+([\\s\\S]+?);\\s")

var headImgReg = regexp.MustCompile("headimg_config:'([\\s\\S]*?)',")

var nameReg = regexp.MustCompile("draw_config:'([\\s\\S]*?)',")

var specialReg = regexp.MustCompile("result_image:'([\\s\\S]*?)',")

func GetGameData(id string) (gameData, headImgCfg, nameCfg, specialData []byte, err error) {
	URL := env.Env.GameUrl(id)
	resp, err := http.Get(URL)
	if err != nil {
		return nil, nil, nil, nil, errors.Wrap(err, "未获得 http 数据")
	}
	defer resp.Body.Close()
	data, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, nil, nil, nil, err
	}
	subs := dataReg.FindSubmatch(data)
	if len(subs) == 0 {
		return nil, nil, nil, nil, errors.Wrap(err, "未获得游戏数据")
	} else {
		gameData = subs[len(subs)-1]
	}
	subs = headImgReg.FindSubmatch(data)
	if len(subs) > 0 {
		headImgCfg = subs[len(subs)-1]
	}
	subs = nameReg.FindSubmatch(data)
	if len(subs) > 0 {
		nameCfg = subs[len(subs)-1]
	}
	subs = specialReg.FindSubmatch(data)
	if len(subs) > 0 {
		specialData = subs[len(subs)-1]
	}
	return gameData, headImgCfg, nameCfg, specialData, nil
}

func GetGameResult(id, option, acid, ext string) (data []byte, err error) {
	resp, err := http.PostForm(env.Env.GetResultUrl(), url.Values{
		"id":     []string{id},
		"option": []string{option},
		"acid":   []string{acid},
		"ext":    []string{ext},
	})
	if err != nil {
		return nil, errors.Wrap(err, "http error")
	}
	defer resp.Body.Close()
	return ioutil.ReadAll(resp.Body)
}

type Order string

const (
	UTime Order = "utime"
	View  Order = "view"
)

func GetSubjects(page string, order Order) (data []byte, err error) {
	var URL string
	switch order {
	case UTime:
		URL = env.Env.UTimeSubjectUrl(page)
	case View:
		URL = env.Env.HotSubjectUrl(page)
	default:
		return nil, errors.New("不允许的排序规则: " + string(order))
	}
	resp, err := http.Get(URL)
	if err != nil {
		return nil, errors.Wrap(err, "http error")
	}
	defer resp.Body.Close()
	return ioutil.ReadAll(resp.Body)
}
